<script setup lang="ts">
import { defineEmits, defineProps, nextTick, onMounted, ref } from 'vue'

const props = defineProps<{
  chatId: string
  title: string
  isSmartAgent?: boolean // 是否为超级智能体
}>()

const emit = defineEmits<{
  (e: 'send-message', message: string): void
}>()

// 聊天消息列表
interface ChatMessage {
  id: string
  content: string
  isUser: boolean
  timestamp: number
}

const messages = ref<ChatMessage[]>([])
const inputMessage = ref('')
const chatContainer = ref<HTMLElement | null>(null)

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return
  
  const message: ChatMessage = {
    id: Date.now().toString(),
    content: inputMessage.value,
    isUser: true,
    timestamp: Date.now()
  }
  
  messages.value.push(message)
  emit('send-message', inputMessage.value)
  inputMessage.value = ''
  
  scrollToBottom()
}

// 添加AI回复消息
const addAIMessage = (content: string) => {
  const message: ChatMessage = {
    id: Date.now().toString() + Math.random(),
    content,
    isUser: false,
    timestamp: Date.now()
  }
  
  messages.value.push(message)
  scrollToBottom()
}

// 更新最后一条AI消息 - 用于超级智能体
const updateLastAIMessage = (content: string) => {
  // 如果是超级智能体，每次接收消息时添加换行
  if (props.isSmartAgent) {
    content = content.replace(/Step\d+:/g, '\n$&')
  }
  
  // 始终添加新消息，而不是更新旧消息
  addAIMessage(content)
  
  scrollToBottom()
}

// 更新现有AI消息 - 用于编程助手
const updateExistingAIMessage = (content: string) => {
  const lastAiMessage = [...messages.value].reverse().find(msg => !msg.isUser)
  
  if (lastAiMessage) {
    lastAiMessage.content = content
  } else {
    addAIMessage(content)
  }
  
  scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}

// 暴露方法给父组件
defineExpose({
  addAIMessage,
  updateLastAIMessage,
  updateExistingAIMessage
})

// 初始欢迎消息
onMounted(() => {
  addAIMessage('你好！我是AI助手，有什么可以帮助你的吗？')
  scrollToBottom()
})
</script>

<template>
  <div class="chat-container">
    <div class="chat-room">
      <div class="chat-header">
        <h2>{{ title }}</h2>
        <div class="chat-id">会话ID: {{ chatId }}</div>
      </div>
      
      <div class="chat-messages" ref="chatContainer">
        <div v-for="message in messages" :key="message.id" 
             :class="['message-wrapper', message.isUser ? 'user-wrapper' : 'ai-wrapper']">
          <div :class="['message', message.isUser ? 'user-message' : 'ai-message']">
            <div class="message-avatar">
              <img v-if="!message.isUser" src="/ai-avatar.jpg" alt="AI" class="avatar-img"
                   onerror="this.src='/ai-default.png'; this.onerror=null;">
              <div v-else class="avatar-text">
                {{ '用户' }}
              </div>
            </div>
            <div class="message-content">
              <div class="message-text" :class="{'ai-text': !message.isUser}">
                <pre v-if="!message.isUser && isSmartAgent">{{ message.content }}</pre>
                <template v-else>{{ message.content }}</template>
              </div>
              <div class="message-time">{{ new Date(message.timestamp).toLocaleTimeString() }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="chat-input">
        <input 
          type="text" 
          v-model="inputMessage" 
          placeholder="请输入消息..." 
          @keyup.enter="sendMessage"
        />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  background-color: #1e1e1e;
}

.chat-room {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  max-width: 800px; /* 限制最大宽度，避免在大屏幕上过宽 */
  border-radius: 0;
  background-color: #1e1e1e;
  color: #f0f0f0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chat-header {
  padding: 15px;
  background-color: #4f46e5;
  color: white;
  border-radius: 0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.chat-header h2 {
  margin: 0;
  font-size: 1.2rem;
}

.chat-id {
  font-size: 0.8rem;
  opacity: 0.8;
  margin-top: 5px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  scroll-behavior: smooth;
  background-color: #1e1e1e;
}

.message-wrapper {
  width: 100%;
  display: flex;
  margin-bottom: 8px;
}

.user-wrapper {
  justify-content: flex-end;
}

.ai-wrapper {
  justify-content: flex-start;
}

.message {
  display: flex;
  max-width: 80%;
}

.user-message {
  flex-direction: row-reverse;
}

.ai-message {
  flex-direction: row;
}

.message-avatar {
  width: 40px;
  height: 40px;
  margin: 0 10px;
  flex-shrink: 0;
}

.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-text {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8rem;
  color: white;
  background-color: #4f46e5;
}

.message-content {
  background-color: #2d2d2d;
  padding: 12px 16px;
  border-radius: 18px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
}

.user-message .message-content {
  background-color: #4f46e5;
  color: white;
  border-top-right-radius: 4px;
}

.ai-message .message-content {
  background-color: #2d2d2d;
  color: #f0f0f0;
  border-top-left-radius: 4px;
}

.message-text {
  word-break: break-word;
  white-space: pre-wrap;
}

.ai-text {
  text-align: left;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: inherit;
  text-align: left;
}

.message-time {
  font-size: 0.7rem;
  color: rgba(255, 255, 255, 0.5);
  margin-top: 5px;
  text-align: right;
}

.chat-input {
  display: flex;
  padding: 15px;
  background-color: #2d2d2d;
  border-top: 1px solid #3a3a3a;
  border-radius: 0;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.chat-input input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #3a3a3a;
  border-radius: 20px;
  margin-right: 10px;
  font-size: 1rem;
  background-color: #3a3a3a;
  color: #f0f0f0;
}

.chat-input button {
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 12px 24px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.chat-input button:hover {
  background-color: #4338ca;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .chat-container {
    height: auto;
    min-height: 100%;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  .chat-room {
    max-width: 100%;
    border-radius: 0;
    height: auto;
    min-height: 100vh;
  }
  
  .chat-messages {
    -webkit-overflow-scrolling: touch;
  }
  
  .message {
    max-width: 90%;
  }
  
  .chat-input {
    padding: 10px;
  }
  
  .chat-input input {
    padding: 10px;
  }
  
  .chat-input button {
    padding: 10px 16px;
  }
}

@media (max-width: 480px) {
  .message {
    max-width: 95%;
  }
  
  .message-avatar {
    width: 32px;
    height: 32px;
    margin: 0 5px;
  }
  
  .chat-header h2 {
    font-size: 1rem;
  }
}

/* 大屏幕优化 */
@media (min-width: 1200px) {
  .chat-room {
    max-width: 800px;
  }
  
  .chat-messages {
    padding: 20px 40px;
  }
  
  .chat-input {
    padding: 20px;
  }
}
</style>
